package com.zyw.boot.tool;

import java.io.*;
/*
* 转换sql文件中表名与字段名
* */
public class SQLFieldNameConverter {

    public static void main(String[] args) {
        String inputFilePath = "D:\\command_db\\main2.sql"; // 输入SQL文件路径
        String outputFilePath = "D:\\command_db\\main3.sql"; // 输出SQL文件路径

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {

            String line;
            while ((line = reader.readLine()) != null) {
                // 处理每一行，将字段名转换为snake_case
                line = convertFieldNamesToSnakeCase(line);
                writer.write(line);
                writer.newLine();
            }

            System.out.println("转换完成，输出文件已保存至: " + outputFilePath);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String convertFieldNamesToSnakeCase(String line) {
        // 匹配字段名的正则表达式
        String regex = "`(\\w+)`";
        StringBuilder result = new StringBuilder();
        Integer lastEnd = 0;

        // 使用正则表达式查找所有字段名
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
        java.util.regex.Matcher matcher = pattern.matcher(line);

        while (matcher.find()) {
            // 添加非匹配部分
            result.append(line, lastEnd, matcher.start());

            // 获取字段名
            String fieldName = matcher.group(1);
            // 将字段名转换为snake_case
            String snakeCaseName = toSnakeCase(fieldName);
            // 添加转换后的字段名
            result.append("`").append(snakeCaseName).append("`");

            lastEnd = matcher.end();
        }

        // 添加剩余部分
        result.append(line.substring(lastEnd));

        return result.toString();
    }

    private static String toSnakeCase(String fieldName) {
        if (fieldName == null || fieldName.isEmpty()) {
            return fieldName;
        }

        StringBuilder snakeCase = new StringBuilder();
        char[] chars = fieldName.toCharArray();

        for (Integer i = 0; i < chars.length; i++) {
            char ch = chars[i];
            if (Character.isUpperCase(ch)) {
                // 如果当前字符是大写字母
                if (i != 0) {
                    // 检查前一个字符是否是小写字母，或者是否是一个连续的大写字母序列的结尾
                    if ('_'!=chars[i - 1] && (Character.isLowerCase(chars[i - 1]) ||
                            (i < chars.length - 1 && Character.isLowerCase(chars[i + 1])))) {
                        snakeCase.append('_');
                    }
                }
                snakeCase.append(Character.toLowerCase(ch));
            } else {
                snakeCase.append(ch);
            }
        }

        return snakeCase.toString();
    }
}